import * as Sequelize from "sequelize";
import { Application } from "egg";

interface OrgAttributes {
  id: string;
  org_name: string;
  org_url?: string;
  remark?: string;
  create_user_id: string;
  modify_user_id: string;
  create_time: string;
  modify_time: string;
}

type OrgInstance = Sequelize.Instance<OrgAttributes> & OrgAttributes;

export default (app: Application) => {
  const { STRING, UUID, UUIDV4, DATE, NOW } = app.Sequelize;
  const attributes: SequelizeAttributes<OrgAttributes> = {
    id: {
      type: UUID,
      primaryKey: true,
      allowNull: false,
      defaultValue: UUIDV4
    },
    org_name: { type: STRING(50), allowNull: false },
    org_url: { type: STRING(255), allowNull: true },
    remark: { type: STRING(255), allowNull: true },
    create_user_id: { type: UUID, allowNull: false },
    modify_user_id: { type: UUID, allowNull: false },
    create_time: { type: DATE, allowNull: false, defaultValue: NOW },
    modify_time: { type: DATE, allowNull: false, defaultValue: NOW }
  };
  const model = app.model.define<OrgInstance, OrgAttributes>(
    "Org",
    attributes,
    {
      tableName: "t_org"
    }
  );
  model.associate = () => {
    app.model.models.Org.hasMany(app.model.models.OrgUser, {
      foreignKey: "org_id",
      sourceKey: "id"
    });
    app.model.models.Org.hasMany(app.model.models.App, {
      foreignKey: "org_id",
      sourceKey: "id"
    });
  };
  return model;
};
